
package cn.springmix.common.sentinel.handle;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 降级 限流策略
 */
@Slf4j
public class SpringmixUrlBlockHandler implements BlockExceptionHandler {

	private static final ObjectMapper objectMapper = new ObjectMapper();

	public ObjectMapper getObjectMapper() {
		return objectMapper;
	}

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
		StringBuffer requestURL = request.getRequestURL();
		String message = null;
		if (e instanceof FlowException) {
			message = "请求接口被限流";
		} else if (e instanceof DegradeException) {
			message = "请求接口被降级";
		} else if (e instanceof ParamFlowException) {
			message = "请求接口被热点限流";
		} else if (e instanceof AuthorityException) {
			message = "请求接口被授权规则限制访问";
		} else if (e instanceof SystemBlockException) {
			message = "请求接口被系统规则限制";
		}
		log.error("{}, 请求路径为:{}", message, requestURL);
		//log.error("sentinel 降级 资源名称{}", e.getRule().getResource(), e);
		String result = getObjectMapper().writeValueAsString(message);
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(result);
	}

}
